import { getMenuAll } from '@/api/sys/menu'
import { getMenusByRole } from '@/api/sys/roleMenu'
import { defineComponent, onMounted, PropType, reactive, watch } from 'vue'

export interface IMenuItem {
  parentId: string;
  menuId: string;
  menuName: string;
  children: IMenuItem[];
  routerName: string;
}

export default defineComponent({
  name: 'MenuTree',
  props: {
    roleId: {
      type: String as PropType<string>,
      default: ''
    }
  },
  setup(props) {
    const state = reactive({
      menuList: [] as IMenuItem[],
      checkedKeys: [] as string[]
    })

    onMounted(() => {
      getMenuAll().then((res) => {
        state.menuList = res.result.records as IMenuItem[]
      })
    })
    watch(() => props.roleId, (val) => {
      getMenusByRole(val).then((res) => {
        state.checkedKeys = res.result.menus
      })
    })
    return () => {
      return (
        <a-card title="角色权限" bordered={false}>
          {
            props.roleId ? (<a-tree
              v-model={[state.checkedKeys, 'checkedKeys']}
              tree-data={state.menuList}
              replaceFields={{ children: 'children', title: 'menuName', key: 'menuId' }}
              checkable
              checkStrictly
            />) : (<a-empty description="请选择配置角色" />)
          }
        </a-card>
      )
    }
  }
})
